
import {
	defineStore
} from 'pinia';
import {
	formatTime
} from './im/index'
import {
	decodeElement
} from './im/decodeElement'
import dayjs from 'dayjs';
import sheep from '@/sheep';
import {
	cloneDeep
} from 'lodash'
import imApi from '@/im/api/index.js'
import {udid} from '@/im/config/index.js'

const im = defineStore({
	id: 'im',
	state: () => ({
		isReady: false, // sdk 是否准备完成
		userInfo: null, // 当前用户的信息
		networkStatus: 'connected', // 网络状态 connected 正常 connecting 连接中  disconnected 网络不可用
		messageList: [], // 聊天首页列表
		keyword: '', // 首页搜索
		isFriend: false, // 单聊是否是好友
		type: '', // 当前增加的消息类型  chat = 私聊   group = 群聊
		chatInfo: {}, // 单聊的详细信息对象
		groupInfo: {}, // 群聊的详细信息对象
		chatMessageList: [], //单聊的聊天记录
		groupMessageList: [], // 群聊的聊天记录
		myGroupList: [], //我的群组
		unreadCount: '', // 好友申请未读数量
		isSystem: false, // 是否是服务助手
		mobile: '', //用户的手机账号
		to: '',
		statusBarHeight: '',
		systemList: [], // 聊天首页平台服务列表
		safe: '',
		unreadNum: 0,
		page: 1,
		total: 1,
		loadStatus: 'loading',
		chat_page: 1,
		chat_loadStatus: '',
		group_page: 1,
		group_loadStatus: '',
		admin_avatar: 'https://liuliangbenben.oss-cn-hangzhou.aliyuncs.com/storage/qita/20250206/6976b65438ffdc063d904039e67150b4.png',
		typeList: [],
		index: 0,
		first: false,
		myUserInfo: {},
		url_data:''
	}),
	actions: {
		// 静态更新数据
		async staticChangeData(data) {
			let self = this;
			if (data.type === 'TIMGroupTipElem' || data.type === 'TIMGroupSystemNoticeElem') {
				return
			}
			if (data.conversationType === 'C2C') {
				if (data.from === "system" || data.from === 'order' || data.from === 'wallet') {
					self.setRead(data.conversationID)
					self.addChatMessage(data, 'chat')
					self.getSystem()
					return
				}
				if (self.type === 'chat' && data.conversationID === self.chatInfo.conversationID) {
					await self.setRead(data.conversationID)
					self.addChatMessage(data, 'chat')
				}
			}
			if (data.conversationType === 'GROUP') {
				// 更新聊天详情页数据 只有匹配到了聊天对象才更新详情页数据
				if (self.type === 'group' && data.conversationID === self.groupInfo.conversationID) {
					await self.setGroupRead()
					self.addChatMessage(data, 'group')
				}
			}
			self.setType();
			self.setMessage();
		},
		setGroupRead() {
			let self = this
			return new Promise(async (resolve, reject) => {
				const {
					code,
					data
				} = await imApi.getMessageDetails({
					from_account: self.userInfo.userID,
					group_id: self.groupInfo.groupProfile.groupID,
					page: 1,
					list_rows: 1
				})

				if (code === 0) {
					resolve()
				}
			})
		},
		// 自己发送的消息 静态添加到首页的消息列表
		mySendAddMessage(data) {
			this.setMessage();
		},
		async getGroupUserInfo(id) {
			let self = this
			const {
				code,
				data
			} = await imApi.groupInfo({
				group_id: self.groupInfo.groupProfile.groupID,
				im_id: id
			})

			if (code === 0) {
				self.myUserInfo.avatar = data.user.avatar
				self.myUserInfo.nickname = data.user.nickname
			}
		},
		async getSystem() {
			let self = this
			const {
				code,
				data
			} = await imApi.getServiceMsgList({
				im_id: self.userInfo.userID
			})

			if (code === 0) {
				self.systemList = data.map(item => {
					item.lastMessage = {
						type: item.msg_body ? JSON.parse(item.msg_body).MsgType : '',
						lastTime: item.msg_body ? self.setTime(item.update_time) : '',
						messageForShow: self.setServiceMsg(item)
					}
					return item
				})
			}
		},
		async addChatMessage(data, type) {
			let self = this
			if (type === 'group') {
				await self.getGroupUserInfo(data.from)
			}
			let chat_data = self.setChatMessageData(data)
			let message = cloneDeep(data)
			message.payload = chat_data ? chat_data : data.payload
			message.userID = message.from
			message.avatar = self.myUserInfo.avatar ? self.myUserInfo.avatar : message.avatar
			message.nick = self.myUserInfo.nickname ? self.myUserInfo.nickname : message.nick
			self.pushChatMessageList(message, type, false, false)
		},
		setRead(conversationID) {
			let self = this
			return new Promise(async (resolve, reject) => {
				await wx.$app.setMessageRead({
					conversationID
				})
				resolve()
			})
		},
		setChatMessageData(data) {
			let obj = null
			if (data.type === 'TIMImageElem') {
				obj = {
					'imageInfoArray': data.payload.imageInfoArray.map(img => ({
						url: img.url
					})),
					'type': data.type
				}
			}
			if (data.type === 'TIMCustomElem') {
				obj = {
					'custom': JSON.parse(data.payload.data),
					'type': data.type
				}
			}
			if (data.type === 'TIMVideoFileElem') {
				obj = {
					'videoUrl': data.payload.videoUrl,
					'videoUrlimg': data.payload.videoUrl + '?ci-process=snapshot&time=0.01'
				}
			}
			if (data.type === "TIMTextElem") {
				obj = {
					'text': data.payload.text,
					'type': data.type
				}
			}
			return obj
		},
		async setMessage() {
			let self = this
			const {
				code,
				data
			} = await imApi.getMessageList({
				im_id: self.userInfo.userID,
				page: 1,
				type: self.typeList[self.index].status,
				list_rows: self.messageList.length
			})

			if (code === 0) {
				self.messageList = data.data.map(item => {
					item.top = item.top_status === 1 ? 1 : 0
					item.lastMessage = {
						lastTime: item.msg_body ? self.setTime(item.update_time) : '',
						messageForShow: item.msg_body ? item.msg_body.MsgType ===
							'TIMCustomElem' ? self.setGroupMsg(item) : item.msg_content : '',
						type: item.msg_body ? item.msg_body.MsgType : ''
					}
					return item
				})
			}
		},
		async setType() {
			let self = this;
			const {
				code,
				data
			} = await imApi.typeList({
				im_id: self.userInfo.userID
			})
			if (code === 0) {
				self.typeList = data
			}
		},
		setUnread(num) {
			this.typeList[this.index].no_read_num = this.typeList[this.index].no_read_num - num
		},
		// 更新了头像昵称之后 将 列表的数据 静态改变一下
		setGroupList(user, id) {
			this.groupMessageList.map(item => {
				if (id === item.userID) {
					item.avatar = user.avatar
					item.nick = user.nickname
				}
				return item
			})
		},
		// 删除了好友之后将首页的列表更新一下
		async resetMessageList() {
			this.page = 1
			await this.changeIndex(this.index)
		},
		clear() {
			this.group_page = 1
			this.group_loadStatus = ''
			this.groupMessageList = []
			this.changeIndex(this.index)
		},
		async changeIndex(index) {
			let self = this
			self.index = index
			self.page = 1
			self.total = 1
			self.messageList = []
			self.loadStatus = 'loading'
			const {
				code,
				data
			} = await imApi.getMessageList({
				im_id: self.userInfo.userID,
				page: self.page,
				type: self.typeList[self.index].status
			})

			if (code === 0) {
				self.total = data.total
				if (data.current_page < data.last_page) {
					self.loadStatus = 'more';
				} else {
					self.loadStatus = 'noMore';
				}
				self.messageList = data.data.map(item => {
					item.top = item.top_status === 1 ? 1 : 0
					item.lastMessage = {
						lastTime: item.msg_body ? self.setTime(item.update_time) : '',
						messageForShow: item.msg_body ? item.msg_body.MsgType ===
							'TIMCustomElem' ? self.setGroupMsg(item) : item.msg_content : '',
						type: item.msg_body ? item.msg_body.MsgType : ''
					}
					return item
				})
			}
		},
		setTop(id, status) {
			this.messageList = this.messageList.map(item => {
				if (item.id === id) {
					item.top = status;
				}
				return item;
			}).sort((a, b) => {
				if (b.top === 1) {
					return 1;
				} else if (a.top === 1) {
					return -1;
				} else {
					return 0;
				}
			});
		},
		deleteMessage(id) {
			let index = this.messageList.findIndex(item => {
				return item.id === id
			})
			if (index !== -1) {
				this.messageList.splice(index, 1)
			}
		},
		logAgain() {
			this.imLogin(sheep.$store('user').userInfo.mobile)
		},
		setTalkList(id) {
			this.messageList = this.messageList.map(item => {
				if (item.account === id) {
					item.unreadCount = 0
				}
				return item
			})
			this.systemList = this.systemList.map(item => {
				if (item.account === id) {
					item.unreadCount = 0
				}
				return item
			})
		},
		// 我的群聊列表
		setMyGroup(data) {
			this.myGroupList = data
		},
		getGroupInfo(conversationID, type = true) {
			let self = this
			wx.$app.setMessageRead({
				conversationID
			})
			self.resetGroup()
			self.type = 'group'
			self.setTalkList(conversationID.split('GROUP')[1])
			wx.$app.getConversationProfile(conversationID).then(res => {
				if (res.code === 0) {
					self.groupInfo = res.data.conversation
					if (type) {
						let name = res.data.conversation.groupProfile.name || res.data.conversation
							.groupProfile.groupID
						uni.navigateTo({
							url: `/im/pages/groupChat?title=${name}&isPinned=${self.groupInfo.isPinned}`
						})
					}
				}
			})
		},
		// 获取会话资料  有两种方式  一个群聊里的成员  一个是好友列表的
		getFriendInfo(conversationID, type) {
			let self = this
			self.resetChat()
			wx.$app.setMessageRead({
				conversationID
			})
			self.type = 'chat'
			self.setTalkList(conversationID.split('C2C')[1])
			self.checkFriend(conversationID.split('C2C')[1])
			wx.$app.getConversationProfile(conversationID).then(res => {
				if (res.code === 0) {
					self.chatInfo = res.data.conversation
					let name = res.data.conversation.userProfile.nick || res.data
						.conversation.userProfile.userID
					uni.navigateTo({
						url: `/im/pages/userInfo?title=${name}&type=${type}`
					})
				}
			})
		},
		checkFriend(userId) {
			return new Promise((resolve, reject) => {
				wx.$app.checkFriend({
					userIDList: [userId],
					type: wx.TIM.TYPES.SNS_CHECK_TYPE_BOTH,
				}).then(res => {
					if (res.code === 0 && res.data.successUserIDList[0] && res.data
						.successUserIDList[0]
						.relation !== 'CheckResult_Type_BothWay') {
						this.isFriend = true
					} else {
						this.isFriend = false
					}
					resolve()
				})
			})
		},
		async pushChatMessageList(message, type = 'chat', request = false, pushMessgae = true) {
			if (type === 'group' && request) {
				await this.getGroupUserInfo(message.from)
				message.avatar = this.myUserInfo.avatar
				message.nickname = this.myUserInfo.nickname
			}
			message.lastMessage = decodeElement(message)
			let date = new Date(message.time * 1000)
			message.newtime = formatTime(date)
			message.status = 'success'
			message.timeString = dayjs(message.time * 1000).format('YYYY-MM-DD HH:mm:ss');
			if (type === 'chat') {
				this.chatMessageList.unshift(message)
				pushMessgae && this.mySendAddMessage(message)
			} else {
				this.groupMessageList.unshift(message)
				pushMessgae && this.mySendAddMessage(message)
			}
			setTimeout(() => {
				uni.pageScrollTo({
					scrollTop: 99999
				})
			}, 100)
		},
		// 会话资料 conversationID = 聊天对象id type=群聊还是私聊 account=只有订单和钱包才会传 jumpType=是否保留当前的页面栈(小程序联系客服直接去掉页面栈)
		async getChatInfo(conversationID, type, account, jumpType = false, groupJump = false) {
			let self = this
			// 将会话消息设置为已读
			wx.$app.setMessageRead({
				conversationID
			})
			// 是否是好友
			if (type === 'chat') {
				self.resetChat()
				if (account !== "wallet" && account !== "order" && account !== "system") {
					self.checkFriend(conversationID.split('C2C')[1])
				} else {
					self.isSystem = true
				}
				// 将列表的聊天标识设置已读
				self.setTalkList(conversationID.split('C2C')[1])
			} else {
				self.resetGroup()
				self.setTalkList(conversationID.split('GROUP')[1])
			}
			self.type = type
			// 获取资料
			wx.$app.getConversationProfile(conversationID).then(res => {
				if (res.code === 0) {
					if (self.type === 'chat') {
						self.chatInfo = res.data.conversation
					} else {
						self.groupInfo = res.data.conversation
						self.getGroupUserInfo()
					}
					let name = ''
					if (self.type === 'chat') {
						name = res.data.conversation.userProfile.nick || res.data.conversation
							.userProfile.userID
						if (jumpType) {
							uni.navigateTo({
								url: `/im/pages/chat?title=${name}&isPinned=${self.chatInfo.isPinned}`
							})
						} else {
							uni.navigateTo({
								url: `/im/pages/chat?title=${name}&isPinned=${self.chatInfo.isPinned}`
							})
						}
					} else {
						name = res.data.conversation.groupProfile.name || res.data.conversation
							.groupProfile.groupID
						if (groupJump) {
							uni.navigateTo({
								url: `/im/pages/groupChat?title=${name}&isPinned=${self.groupInfo.isPinned}`
							})
						} else {
							uni.navigateTo({
								url: `/im/pages/groupChat?title=${name}&isPinned=${self.groupInfo.isPinned}`
							})
						}
					}
				}
			})
		},
		handleMessage(obj) {

			const msgType = obj.msg_body.MsgType

			const mapping = {
				'TIMImageElem': 'imageInfoArray',
				'TIMSoundElem': 'url',
				'TIMFaceElem': 'data',
				'TIMVideoFileElem': 'videoUrl',
				'TIMCustomElem': 'custom'
			};

			const typeMapping = {
				TIMSoundElem: 'second',
				TIMVideoFileElem: 'videoUrlimg'
			};

			const typeHandlers = {
				TIMSoundElem: (objs) => objs.msg_body.MsgContent.Second,
				TIMVideoFileElem: (objs) => objs.msg_body.MsgContent.VideoUrl +
					'?ci-process=snapshot&time=0.01',
				default: (objs) => objs.msg_body.MsgType
			};

			const handlers = {
				TIMImageElem: (objs) => obj.msg_body.MsgContent.ImageInfoArray.map(img => ({
					url: img.URL
				})),
				TIMSoundElem: (objs) => objs.msg_body.MsgContent.Url,
				TIMFaceElem: (objs) => objs.msg_body.MsgContent.Data,
				TIMVideoFileElem: (objs) => objs.msg_body.MsgContent.VideoUrl,
				TIMCustomElem: (objs) => JSON.parse(objs.msg_body.MsgContent.Data),
				default: (objs) => objs.msg_body.MsgContent.Text
			};

			const result = mapping[msgType] || 'text';
			const result2 = typeMapping[msgType] || 'type'

			let result_obj = {}

			result_obj[result] = handlers[msgType] ? handlers[msgType](obj) : handlers.default(obj)
			result_obj[result2] = typeHandlers[msgType] ? typeHandlers[msgType](obj) : typeHandlers
				.default(obj)
			return result_obj
		},
		// 私聊记录
		async getChatMessageList(page) {
			let self = this
			if (self.chat_loadStatus === 'noMore') {
				return sheep.$helper.toast('没有更多啦')
			}
			return new Promise(async (resolve, reject) => {
				const {
					code,
					data
				} = await imApi.getMessageDetails({
					from_account: self.userInfo.userID,
					to_account: self.chatInfo.userProfile.userID,
					page: page
				})
				if (code === 0) {
					data.data = data.data.map(item => {
						return {
							id: item.id,
							to: self.userInfo.userID,
							conversationID: self.chatInfo.userProfile.userID,
							conversationType: self.chatInfo.type,
							userID: item.from_account,
							status: 'success',
							time: item.create_time.replace(/-/g, '/'),
							timeString: item.create_time,
							type: item.msg_body.MsgType,
							from: item.from_account,
							flow: (item.from_account === self.userInfo.userID) ?
								'out' : 'in',
							nick: item.nickname,
							avatar: item.avatar,
							payload: self.handleMessage(item)
						}
					})
					resolve(data.data)
					if (data.current_page < data.last_page) {
						self.chat_loadStatus = 'more';
					} else {
						self.chat_loadStatus = 'noMore';
					}
				}
			})
		},
		// 群聊记录
		async getGroupMessageList(page) {
			let self = this
			if (self.group_loadStatus === 'noMore') {
				return sheep.$helper.toast('没有更多啦')
			}
			return new Promise(async (resolve, reject) => {
				let res = await wx.$app.getGroupMemberList({
					groupID: self.groupInfo.groupProfile.groupID
				})
				let memberList = res.data.memberList || []
				const {
					code,
					data
				} = await imApi.getMessageDetails({
					from_account: self.userInfo.userID,
					group_id: self.groupInfo.groupProfile.groupID,
					page: page
				})
				uni.hideLoading()
				if (code === 0) {
					data.data = data.data.map(item => {
						return {
							id: item.id,
							conversationID: self.groupInfo.groupProfile.groupID,
							conversationType: self.groupInfo.type,
							userID: item.from_account,
							status: 'success',
							time: item.create_time.replace(/-/g, '/'),
							timeString: item.create_time,
							type: item.msg_body.MsgType,
							from: item.from_account,
							fans: item.fans,
							role_name: item.role_name,
							flow: (item.from_account == self.userInfo.userID) ? 'out' :
								'in',
							nick: item.from_account === 'administrator' ?
								'管理员' : item.nickname,
							avatar: item.from_account ==
								'administrator' ? self.admin_avatar : item.avatar,
							payload: self.handleMessage(item)
						}
					})
					resolve(data.data)
					if (data.current_page < data.last_page) {
						self.group_loadStatus = 'more';
					} else {
						self.group_loadStatus = 'noMore';
					}
				}
			})
		},
		unshiftMessageList(messageList) {
			if (!messageList) {
				return 
			}
			let list = [...messageList]
			for (let i = 0; i < list.length; i++) {
				let message = list[i]
				list[i].lastMessage = decodeElement(message)
				let date = new Date(message.time * 1000)
				list[i].newtime = formatTime(date)
				list[i].newtime = date
			}
			if (this.type === 'chat') {
				this.chatMessageList = [...this.chatMessageList, ...list]
			} else {
				this.groupMessageList = [...this.groupMessageList, ...list]
			}
		},
		// 设置状态
		async setIsReady(data) {
			this.isReady = data
			if (this.isReady) {
				if (!this.userInfo) {
					await this.getMyUserInfo()
				} else {
					this.getMessageList()
				}
			}
		},
		// 获取首页会话列表
		getMessageList(data) {
			let self = this
			self.messageList = []
			self.systemList = []
			self.page = 1
			self.first = false
			this.allGetMessage()
		},
		async getMsgList() {
			let self = this
			self.loadStatus = 'loading'
			const {
				code,
				data
			} = await imApi.getMessageList({
				im_id: self.userInfo.userID,
				page: self.page,
				type: self.typeList[self.index].status
			})

			if (code === 0) {
				data.data = data.data.map(item => {
					item.top = item.top_status === 1 ? 1 : 0
					item.lastMessage = {
						lastTime: item.msg_body ? self.setTime(item.update_time) : '',
						messageForShow: item.msg_body ? item.msg_body.MsgType ===
							'TIMCustomElem' ? self.setGroupMsg(item) : item.msg_content : '',
						type: item.msg_body ? item.msg_body.MsgType : ''
					}
					return item
				})
				self.messageList = self.messageList.concat(data.data)
				if (data.current_page < data.last_page) {
					self.loadStatus = 'more';
				} else {
					self.loadStatus = 'noMore';
				}
			}
		},
		async allGetMessage() {
			let self = this
			self.loadStatus = 'loading'
			const {
				code,
				data
			} = await imApi.typeList({
				im_id: self.userInfo.userID
			})
			if (code === 0) {
				self.typeList = data
			}
			Promise.all([imApi.getServiceMsgList({
				im_id: self.userInfo.userID
			}), imApi.getMessageList({
				im_id: self.userInfo.userID,
				page: self.page,
				type: self.typeList[self.index].status
			})]).then(res => {
				self.systemList = res[0].data.map(item => {
					item.lastMessage = {
						type: item.msg_body ? JSON.parse(item.msg_body).MsgType : '',
						lastTime: item.msg_body ? self.setTime(item.update_time) : '',
						messageForShow: self.setServiceMsg(item)
					}
					return item
				})
				self.total = res[1].data.total
				if (res[1].data.current_page < res[1].data.last_page) {
					self.loadStatus = 'more';
				} else {
					self.loadStatus = 'noMore';
				}
				self.messageList = res[1].data.data.map(item => {
					item.top = item.top_status === 1 ? 1 : 0
					item.lastMessage = {
						lastTime: item.msg_body ? self.setTime(item.update_time) : '',
						messageForShow: item.msg_body ? item.msg_body.MsgType ===
							'TIMCustomElem' ? self.setGroupMsg(item) : item
							.msg_content : '',
						type: item.msg_body ? item.msg_body.MsgType : ''
					}
					return item
				})
				self.first = true
			})
		},
		setTime(timestamp) {
			return dayjs.unix(timestamp).format('YYYY-MM-DD HH:mm:ss');
		},
		setServiceMsg(msg) {
			if (msg.msg_content) {
				if (msg.platform_im_id === "wallet") {
					let obj = JSON.parse(msg.msg_content)
					return obj.money_msg
				} else if (msg.platform_im_id === "order") {
					let obj = JSON.parse(msg.msg_content)
					return obj.order_status_title
				} else if (msg.platform_im_id === "system") {
					let obj = JSON.parse(msg.msg_content)
					return obj.title
				}
				let obj = JSON.parse(msg.msg_content)
				if (obj.type === 'find') {
					return obj.file_type === 'image' ? '分享图文' : '分享视频'
				}
				let Enum = {
					'goods': '[商品]',
					'activity': obj.title,
					'group': '特邀您入群',
					'red': '[红包]',
					'coupon': obj.title,
					'share_order': '请您确认收货地址'
				}
				return Enum[obj.type]
			}
			return ''
		},
		setGroupMsg(msg) {
			if (msg.msg_content) {
				let obj = JSON.parse(msg.msg_content)
				if (obj.type === 'find') {
					return obj.file_type === 'image' ? '分享图文' : '分享视频'
				}
				let Enum = {
					'goods': '[商品]',
					'activity': obj.title,
					'group': '特邀您入群',
					'red': '[红包]',
					'coupon': obj.title,
					'share_order': '请您确认收货地址'
				}
				return Enum[obj.type]
			}
			return ''
		},
		// 获取用户信息
		getMyUserInfo() {
			let self = this
			wx.$app.getMyProfile().then(res => {
				self.userInfo = res.data
				// 修改用户添加好友的通过方式
				if (res.data.allowType !== 'AllowType_Type_NeedConfirm') {
					wx.$app.updateMyProfile({
						allowType: 'AllowType_Type_NeedConfirm'
					}).then(imResponse => {
						self.userInfo = imResponse.data
					})
				}
				self.getMessageList()
			})
		},
		setNetwork(data) {
			this.networkStatus = data
		},
		showNetwork() {
			if (this.networkStatus === 'disconnected') {
				uni.showModal({
					title: '提示',
					content: '当前网络不可用',
				});
			}

			if (this.networkStatus === 'connecting') {
				uni.showModal({
					title: '提示',
					content: '当前网络不稳定',
				});
			}
		},
		setKeyword(data) {
			this.keyword = data
		},
		// 重置数据
		resetChat() {
			this.isFriend = false
			this.chatInfo = {}
			this.chatMessageList = []
			this.chat_loadStatus = ''
			this.isSystem = false
			this.type = ''
		},
		resetGroup() {
			this.groupInfo = {}
			this.groupMessageList = []
			this.group_loadStatus = ''
			this.type = ''
		},
		imLogin(mobile) {
			let self = this
			if (!mobile) {
				let self = this
				self.messageList = []
				self.systemList = []
				return
			}
			return new Promise(async (resolve, reject) => {
				const {
					code,
					data,
					msg
				} = await imApi.login({
					mobile: mobile
				})
				if (code === 0) {
					const result = await imApi.createSign({
						identifier: data.im_id
					})
					if (result.code === 1) {
						wx.$app.login({
							userID: data.im_id,
							userSig: result.data.userSig
						}).then((response) => {
							resolve()
						}).catch((err) => {
							reject()
						})
					}
				}
			})
		},
		webQueryAnalysis(data){
			let {aim,service} = data
			console.log('webQueryAnalysis',aim,service.mobile)
			this.NextOperate(aim,service.mobile)
		},
		NextOperate(type,mobile) {
			let self = this
			const aimActions = {
				service: async () => {
					uni.showLoading({
						title: '拉起客服聊天中'
					});
					const {code,data} = await imApi.login({
						mobile: mobile
					})
					if (code === 0) {
						uni.hideLoading();
						self.getChatInfo(`C2C${data.im_id}`, 'chat','', true)
					}
				},
				addFriend: async () => {
					uni.showLoading({
						title: '查询用户中'
					});
					const {code,data} = await imApi.login({
						mobile: mobile
					})
					if (code === 0) {
						const res = await wx.$app.addFriend({
							to: data.data.im_id,
							source: 'AddSource_Type_Web',
							type: wx.TIM.TYPES.SNS_ADD_TYPE_BOTH,
						});
						uni.hideLoading();
						if (res.data.code === 30539) {
							uni.showToast({
								title: res.data.message,
								icon: 'none'
							})
						} else {
							uni.showToast({
								title: '添加失败!请稍后再试',
								duration: 1500,
								icon: 'none'
							});
						}
					}
				},
				addGroup: () => {
					wx.$app.joinGroup({
							groupID: mobile,
							applyMessage: '我想申请加入贵群，望批准！'
						})
						.then((e) => {
							wx.showModal({
								title: '提示',
								content: '加群成功，是否立即前往？',
								confirmText: '立即前往',
								success: (res) => {
									if (res.confirm) {
										self.getChatInfo(mobile, 'group')
									}
								},
							})
							imApi.addGroup({
								type: udid,
								group_id: mobile,
								to_account: self.userInfo.userID,
								from_account: ''
							})
						})
						.catch((err) => {
							console.log(err)
						})
				},
				message: async () => {
					uni.showLoading({
						title: '拉起聊天中'
					});
					const {code,data} = await imApi.login({
						mobile: mobile
					})
					if (code === 0) {
						uni.hideLoading();
						// #ifdef H5
						self.getChatInfo(`C2C${data.im_id}`, 'chat','', true)
						// #endif
					}
				},
				groupMessage: () => {
					uni.showLoading({
						title: '查找群聊中'
					});
					setTimeout(() => {
						uni.hideLoading();
						self.getChatInfo(mobile, 'group', '',true)
					}, 500)
				}
			};
			
			const action = aimActions[type] || (() => {});
			action();
		}
	},
	persist: {
		enabled: true,
		strategies: [{
			key: 'im-store',
		}, ],
	},
});

export default im;